package org.kojo.tdrm.dao;

import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public abstract class AbstractDao<T> {
	private Class<T> entityClass;

	public AbstractDao(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	protected abstract PersistenceManager getPersistenceManager();

	public void create(T entity) {
		PersistenceManager pm = getPersistenceManager();
		try {
			System.out.println("create="+entity.toString());
			pm.makePersistent(entity);
		} finally {
			pm.close();
		}
	}

	public void edit(T entity) {
		getPersistenceManager().makePersistent(entity);
	}

	public void remove(T entity) {
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.deletePersistent(entity);
			pm.flush();
		} finally {
			
		}
	}

	public T find(Object id) {
		T entity = null;
		PersistenceManager pm = getPersistenceManager();
		try {
			entity = pm.getObjectById(entityClass, id);
		} catch(JDOObjectNotFoundException ex){
			System.out.println("Not Found object "+id);
		} finally {
			
		}
		return entity;
	}

	public List<T> findAll() {
		List<T> o = null;
		PersistenceManager pm = getPersistenceManager();
		try {
			Query q = pm.newQuery(entityClass);
			o = (List<T>) q.execute();
			
		} finally {
			
		}
		return o;
	}

	public List<T> findRange(long start, long end) {
		List<T> o = null;
		PersistenceManager pm = getPersistenceManager();
		try {
			Query q = getPersistenceManager().newQuery(entityClass);
			q.setRange(start, end);
			o = (List<T>) q.execute();
		} finally {
			
		}
		return o;
	}

	public int count() {
		return 0;
	}
}
